package util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * JDBC操作工具类
 */
public class JdbcUtil {

    /**
     * 执行增删改
     * @param sql
     * @param params
     */
    public static void executeUpdate(String sql,Object... params) throws SQLException {
        //创建连接
        try(Connection connection = DataSourceUtil.getConnection()){
            //创建PreparedStatement
            PreparedStatement ps = connection.prepareStatement(sql);
            //设置占位符
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1,params[i]);
            }
            //执行更新
            int row = ps.executeUpdate();
            if(row == 0){
                throw new SQLException("更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 查询方法
     */
    public static <T> List<T> executeQuery(Class clazz, String sql, Object... params) throws SQLException {
        //创建连接
        try(Connection connection = DataSourceUtil.getConnection()){
            //创建PreparedStatement
            PreparedStatement ps = connection.prepareStatement(sql);
            //设置占位符
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1,params[i]);
            }
            //执行查询
            ResultSet resultSet = ps.executeQuery();
            List<T> objects = new ArrayList<>();
            while(resultSet.next()){
                //反射创建实体类对象
                Object obj = clazz.newInstance();
                //获得所有的属性
                Field[] fields = clazz.getDeclaredFields();
                for(Field field : fields){
                    //读取属性对应列的值
                    Object value = resultSet.getObject(field.getName());
                    //设置可访问
                    field.setAccessible(true);
                    //给属性赋值
                    field.set(obj,value);
                }
                objects.add((T) obj);
            }
            return objects;
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询一个对象
     */
    public static <T> T queryOne(Class clazz, String sql, Object... params) throws SQLException {
        List<T> objects = executeQuery(clazz,sql,params);
        if(objects != null && objects.size() > 0){
            return objects.get(0);
        }
        return null;
    }
}
